rm(list=ls())
library(statnet)
setwd("C:\\Documents and Settings\\Laura Metzger\\Desktop\\Dissertation\\Chapter2\\Data\\")
data<-read.csv("NC05.csv")
load("NCnet05.RData")

AMnet<-network(AM)
r<-as.vector(AM)
r<-r[r!=0]
set.edge.attribute(AMnet, "values", r, e=1:length(r))
AMnet<-network.adjacency(AM, AMnet, ignore.eval=FALSE, names.eval="values")
get.edge.attribute(AMnet$mel, "values")

same.party<-matrix(0, 123, 123)
for(i in 1:123){
for(j in 1:123){
same.party[i,j]<-ifelse(data$party[i]==data$party[j], 1, 0)
}
}


#share<-read.csv("99Shared.csv")
#q<-share[,2]
#p<-share[,3]
#z<-row.names(AM)
#same.dist<-matrix(0, 123, 123)
#for(i in 1:176){
#for(j in 1:176){
#a<-match(q[i], z)
#b<-match(p[i], z)
#if(is.na(a)==FALSE & is.na(b)==FALSE){
#same.dist[a,b]<-1
#same.dist[b,a]<-1
#}
#}
#}

same.dist<-matrix(0, 123, 123)
for(i in 1:123){
for(j in 1:123){
same.dist[i,j]<-ifelse(data$dist[i]==data$dist[j], 1, 0)
}
}
same.dist<-ifelse(is.na(same.dist)==TRUE, 0, same.dist)

diag(same.dist)<-0

vec1<-as.vector(same.party)
vec2<-as.vector(same.dist)
vec3<-vec1*vec2
interact<-matrix(vec3, ncol=123)


mod<-ergmm(AMnet~latentcov(same.party)+latentcov(same.dist)+latentcov(interact)+latent(d=2), family="Poisson", response="values", verbose=1, control=ergmm.control(sample=20000, burnin=20000))

dput(mod, file="results052.txt")
dput(summary(mod), file="summary052.txt")
summary(mod)

r<-predict.ergmm(mod)
f<-AM-r

pdf("DensityDifference052.pdf")
plot(density(f), main="Density of Differences between Observed and Predicted Connections", xlab="Difference in Connections")
dev.off()

pdf("DensityObsPre052.pdf")
plot(density(AM), col="red", xlim=c(-5, 20), main="Density of Observed and Predicted Connections in the NC House")
lines(density(r), col="blue", xlim=c(-5, 20))
legend(10, 0.25, c("Observed","Predicted"), col=c("red", "blue"), lty=c(1,1))
dev.off()

pdf("positions052.pdf")
plot(mod, vertex.col=data$party+1, main="MKL Latent Positions of NC House in 2005", label=TRUE, edge.col=0, what="mkl")
abline(0,0)
abline(v=0)
legend(-5, 6, c("Democrats","Republicans"), col=c("red","black"), lty=c(1,1), lwd=c(2,2))
dev.off()
